package de.upb.messerschmidt.set;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.upb.messerschmidt.set.entity.Person;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * Gets a {@link Person}'s data via an HttpPost and persists it.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class RegisterPersonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String firstName = req.getParameter("firstName");
		String lastName = req.getParameter("lastName");
		String company = req.getParameter("company");
		String email = req.getParameter("email");
		String token = req.getParameter("token");
		String secret = req.getParameter("secret");

		if (firstName == null || lastName == null || email == null
				|| token == null || secret == null) {
			resp.setStatus(400);
			resp.getWriter().println(
					"Registration failed - please fill in all fields");
		} else {
			Person person = null;

			PersistenceManager pm = PMF.get().getPersistenceManager();

			if (company == null) {
				company = "";
			}

			Query personQuery = pm.newQuery(Person.class);
			personQuery
					.setFilter("name == nameParam && prename == prenameParam");
			personQuery
					.declareParameters("String nameParam, String prenameParam");

			List<Person> personList = (List<Person>) personQuery.execute(
					lastName, firstName);

			if (!personList.isEmpty()) {
				person = personList.get(0);
				person.setCompany(company);
				person.setEmail(email);
				person.setToken(token);
				person.setSecret(secret);

				pm.flush();
				pm.close();

				resp.setStatus(200);
				resp.getWriter().println("Registration successfully updated");
			} else {
				person = new Person(lastName, firstName, company, email, token,
						secret);
				try {
					pm.makePersistent(person);

					resp.setStatus(200);
					resp.getWriter().println("Registration successfull");
				} catch (Exception e) {
					resp.setStatus(400);
					resp.getWriter().println("Registration failed");
					e.printStackTrace();
				} finally {
					pm.close();
				}
			}
		}
	}

}
